package eventplanner.ejb.dao;

import eventplanner.entities.Event;
import eventplanner.entities.Feed;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Stateless
public class EventDao {

	@PersistenceContext
	private EntityManager em;

	/**
	 * Creates a new event, persists it to the db and adds it to the feed.
	 */
	public void createAndAddEvent(Feed feed, String title, String description, Date start, Date end, String... tags) {
		Event event = new Event();
		event.setTitle(title);
		event.setDescription(description);
		event.setStart(start);
		event.setEnd(end);
		event.setTags(Arrays.asList(tags));

		em.persist(event);
		feed.addEvent(event);
	}

	/**
	 * Creates an event, persists it to the database and adds it to the feed.
	 *
	 * @param time The duration of the event
	 * @param unit The time-unit for the time duration e.g. Hours, Days, Minutes
	 */
	public void createAndAddEvent(Feed feed, String title, String description, Date start, int time, TimeUnit unit, String... tags) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(start);
		int dateUnit = unit == TimeUnit.HOURS ? Calendar.HOUR : unit == TimeUnit.DAYS ? Calendar.DAY_OF_YEAR : Calendar.MINUTE;
		calendar.add(dateUnit, time);
		createAndAddEvent(feed, title, description, start, calendar.getTime(), tags);
	}

	/**
	 * Persists the event to the database
	 */
	public void persist(Event event) {
		em.persist(event);
	}
}
